package cn.lili.timetask.handler.impl.order;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.client.SmsClient;
import cn.lili.modules.system.entity.dos.Dictionary;
import cn.lili.modules.system.entity.params.SmsParams;
import cn.lili.modules.verification.entity.enums.VerificationEnums;
import cn.lili.timetask.handler.EveryMinuteExecute;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 心跳检测，海关地址是否可达
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HeartbeatTaskExecute implements EveryMinuteExecute {

    private final DictionaryClient dictionaryClient;

    private final StringRedisTemplate stringRedisTemplate;

    private final SmsClient smsClient;

    //检查域名能否正常访问
    public boolean checkDomainAvailability(String domain) {
        try {
            HttpRequest httpRequest = HttpUtil.createGet(domain + "/rpc/eport/upload/heartbeat");
            String responseBody = httpRequest.execute().body();
            log.info("responseBody == {}", responseBody);
            return "true".equals(responseBody);
        } catch (Exception e) {
            System.out.println("无法连接到域名：" + domain);
        }
        return false;
    }

    @Override
    public void execute() {
        List<Dictionary> sendCustoms = dictionaryClient.getListByCode("send_customs");
        log.info("sendCustoms == {}", JSONObject.toJSONString(sendCustoms));
        if (CollectionUtil.isEmpty(sendCustoms)) {
            return;
        }
        List<String> urlList = new ArrayList<>();
        for (Dictionary sendCustom : sendCustoms) {
            //检查路径是否可达，可达加入到。redis请求路径列表中
            boolean domainAvailability = this.checkDomainAvailability(sendCustom.getValueName());
            if (domainAvailability) {
                urlList.add(sendCustom.getValueName());
            }
        }
        log.info("urlList == {}", JSONObject.toJSONString(urlList));
        if (CollectionUtil.isEmpty(urlList)) {
            log.error("海关无可用地址");
            //发短信通知报错
            SmsParams smsParams = new SmsParams();
            smsParams.setMobile("17373348393");
            smsParams.setVerificationEnums(VerificationEnums.LOGIN);
            smsParams.setUuid(UUID.randomUUID().toString());
            smsClient.sendSmsCode(smsParams);
        }
        String join = String.join(",", urlList);
        log.info("join == {}", join);
        stringRedisTemplate.opsForValue().set("send_customs", join);;
    }
}
